﻿"use strict";
(function($, window, document, undefined) {

	isperp.dialogOpenedCount = 1;
	isperp.isValidate = false;
	isperp.windowWidth = $(window.top).width();
	isperp.windowHeight = $(window.top).height();
	isperp.windowWidthHeightPer = isperp.windowWidth / isperp.windowHeight;// 屏幕比例

	isperp.windowWidthBig = isperp.windowHeight * (isperp.windowWidthHeightPer - (isperp.windowWidthHeightPer > 1.6 ? 0.20 : 0.06));
	isperp.windowWidthBig = isperp.windowWidthBig > 1000 ? 1000 : isperp.windowWidthBig;
	isperp.appConfig = {
		width : isperp.windowWidth,
		height : isperp.windowHeight,
		windowSize : {
			"greatBig" : [isperp.windowWidthBig * 1.05, isperp.windowHeight * 0.88 ],
			"big" : [ isperp.windowWidthBig, isperp.windowHeight * 0.88 > 510 ? isperp.windowHeight * 0.88 : 510 ],
			"normal" : [ isperp.windowWidthBig * 0.7, isperp.windowHeight * 0.68 > 470 ? isperp.windowHeight * 0.68 : 470 ],
			"small" : [ isperp.windowWidthBig * 0.45, isperp.windowHeight * 0.5 ]
		},
		style : {
			"sail" : {
				background : "url(img/webos/wallpaper/sail.jpg) repeat",
				name : "静海远航"
			},
			"green" : {
				background : "url(img/webos/wallpaper/green.jpg) repeat",
				name : "青青世界"
			},
			"cloud" : {
				background : "url(img/webos/wallpaper/cloud.jpg) repeat",
				name : "晴空行云"
			},
			"grass" : {
				background : "url(img/webos/wallpaper/grass.jpg) repeat",
				name : "茫茫野草"
			},
			"wood" : {
				background : "url(img/webos/wallpaper/wood.jpg) repeat",
				name : "温馨木纹"
			},
			"texture" : {
				background : "url(img/bg.jpg) repeat",
				name : "质感之美"
			},
			"aliceblue" : {
				background : "aliceblue",
				name : "浅蓝纯色"
			},
			"midAutumn" : {
				background : "url(img/webos/wallpaper/midAutumn.jpg) repeat   ",
				name : "中秋之月"
			},
			"dandelionDream" : {
				background : "url(img/webos/wallpaper/dandelionDream.jpg) repeat   ",
				name : "蒲公英"
			}

		}

	};

	isperp.initStyle = function(key) {
		if (key) {
			$("#wallpapers").css("background", isperp.appConfig.style[key].background);
		} else {
			$("#wallpapers").css("background", isperp.appConfig.style["sail"].background);
		}

	};

	isperp.getDialogOpenedCount = function() {
		return window.top.isperp.dialogOpenedCount;
	};

	isperp.tooltip = function(msg, options, useTop, speed) {
		if (useTop != true) {
			window.top.isperp.tooltip(msg, options, true, speed);
		} else {
			var ele = $("#toastMessage");
			if (ele.length == 0) {
				$("body").append('<div id="toastMessage" class="toast-msg"></div>');
				ele = $("#toastMessage");
			}
			var left = isperp.appConfig.width / 2.5;
			ele.css("left", left + "px");
			ele.html(msg);
			if ("fastest" == speed) {
				ele.fadeIn(100);
				ele.delay(400).fadeOut(200);
			} else {
				ele.fadeIn(500);
				ele.delay(3000).fadeOut(1000);
			}

		}
	};
	isperp.alert = function(msg, opt, useTop) {

		if (useTop != true) {
			window.top.isperp.alert(msg, opt, true);
		} else {
			opt = opt || {};
			var type = opt.type || "info";
			var html = '<div class="dialog"><div style="padding:10px;font-size:14px">';

			if (!opt.noIcon) {
				html = html + '<span class="alert-' + type + '"></span>';
			}

			var html = html + msg + '  </div></div>';

			return $(html).dialog({
				resizable : false,
				modal : true,
				show : false,
				hide : false,
				title : opt.title || "提示信息",
				buttons : {
					"关闭" : function() {
						var dlg = $(this).dialog("close");
					}
				}
			});

		}
	};

	isperp.infoAlert = function(msg) {
		isperp.alart(msg);

	};

	isperp.errorAlert = function(msg) {
		isperp.alert(msg, {
			type : "error",
			title : "错误提示"
		});
	};

	isperp.confirmAlert = function(msg, opt, useTop) {
		if (useTop != true) {
			window.top.isperp.confirmAlert(msg, opt, true);
		} else {
			var html = '<div class="dialog"><div style="padding:10px;font-size:14px"><span class="alert-confirm"></span>' + msg + '  </div>' + '</div>';
			opt = opt || {};
			return $(html).dialog({
				resizable : false,
				modal : true,
				show : false,
				hide : false,
				title : opt.title || "操作确认",
				buttons : [ {
					text : "确定",
					"class" : "nui-mainbtn",
					click : function() {
						opt.yes && opt.yes.call(dlg);
						var dlg = $(this).dialog("close");
					}
				}, {
					text : "取消",
					click : function() {
						var dlg = $(this).dialog("close");

					}

				} ]
			});
		}
	};

	isperp.createGridAction = function(options) {
         return "<span  class='ui-pg-div ui-inline-action ui-grid-caction'><span  title='" + options.title + "' class='ui-icon  ui-grid-action " + options.iconCls + "' onclick=\"" + options.onclick + "\"></span></span>";
	};

	isperp.statusFormatter = function(cellvalue) {

		if (cellvalue == true || cellvalue == '在职' || cellvalue == '启用')
			return "<img title='" + cellvalue + "' src='img/icons/packs/fugue/24x24/tick.png'>";
		else
			return "<img title='" + cellvalue + "' src='img/icons/packs/fugue/24x24/minus-circle.png'>";
	};

	isperp.workflow = {};
	isperp.workflow.transferAssignee = function(processId, pcontrolid) {
		isperp.openDialog({
			contentUrl : "workflow/processRun/transferAssigneeEdit?processId=" + processId + (pcontrolid ? "&pcontrolid=" + pcontrolid : ""),
			width : 660,
			height : 480,
			title : "转派处理人"
		});
	};

	isperp.viewUser = function(name) {
		isperp.openDialog({
			"contentUrl" : "app/user/view?name=" + name,
			windowSize : "normal"
		});
	},

	isperp.toString = function(obj) {
		return JSON.stringify(obj);
	};

	isperp.setCheckbox = function(selector, vstr) {
		if (vstr && vstr != "") {
			var itemArr = vstr.split(",");
			for ( var i = 0; i < itemArr.length; i++) {
				var itemValue = itemArr[i];
				$(selector).each(function(index, item) {
					if ($(this).val() == itemValue) {
						$(this).attr("checked", true);
					}
				});
			}
		}
	};

	isperp.changeUrlParam = function(str, name, value) {

		var reg = new RegExp("(^|)" + name + "=([^&]*)(|$)");
		var tmp = name + "=" + value;
		if (str.match(reg) != null) {
			return str.replace(eval(reg), tmp);
		} else {
			if (this.match("[\?]")) {
				return str + "&" + tmp;
			} else {
				return str + "?" + tmp;
			}
		}
	};

	isperp.getUrlParamByName = function(name) {

		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);

		if (r != null)
			return unescape(r[2]);
		return undefined;
	};

	isperp.showDialog = function(options) {
		if (!options)
			options = {};
		var dialogWidth = 700;
		var dialogHeight = 460;
		options = $.extend({}, {
			dialogWidth : dialogWidth,
			dialogHeight : dialogHeight,
			help : 0,
			status : 0,
			scroll : 0,
			center : 1
		}, options);

		if (options.contentUrl) {
			options.url = options.contentUrl;
		}
		var winArgs = "dialogWidth=" + options.dialogWidth + "px;dialogHeight=" + options.dialogHeight + "px;help=" + options.help + ";status=" + options.status + ";scroll=" + options.scroll + ";center=" + options.center;
		var rtn = window.open(options.url, "", winArgs);
	};

	isperp.openDialog = function(options) {
		if (options.onThisWindow) {
			isperp.openDialogMethod(options);
			return;
		}
		if (!options.id) {
			options.id = "dialog_" + window.top.isperp.dialogOpenedCount;
		}
		window.top.isperp.openDialogMethod(options);

	};

	isperp.openDialogMethod = function(options) {

		var $dialog = $("#" + options.id);

		if ($dialog.length == 0) {
			var dialogDiv = "<div id='" + options.id + "' style='-webkit-overflow-scrolling:touch; overflow-y:hidden;'></div>";
			$(dialogDiv).appendTo("body");
			$dialog = $("#" + options.id);
		}

		isperp.dialogOpenedCount = isperp.dialogOpenedCount + 1;
		setDialogOptions(options);
		var d = $($dialog).wijdialog(options);
		return d;
	};

	function setDialogOptions(options) {
		options = options || {};
		options.modal = options.modal === false ? false : true;
		if (!options.title) {
			options.title = "操作窗口";
		}
		if (options.autoOpen != false)
			options.autoOpen = true;
		if (!options.resizable) {
			options.resizable = true;
		}

		if (options.maximize || options.windowSize == "maximize") {
			options.width = $(window).width();
			options.height = $(window).height();
		} else {

			if (options.windowSize && options.windowSize != "") {
				if (options.onThisWindow) {
					options.width = isperp.appConfig.windowSize[options.windowSize][0] - 80;
					options.height = isperp.appConfig.windowSize[options.windowSize][1] - 50;
				} else {
					options.width = isperp.appConfig.windowSize[options.windowSize][0];
					options.height = isperp.appConfig.windowSize[options.windowSize][1];
				}

			}

			if (!options.width || options.width == "") {

				if (options.onThisWindow) {
					options.width = isperp.appConfig.windowSize["big"][0] - 100;
				} else {
					options.width = isperp.appConfig.windowSize["big"][0];
				}
			}

			if (!options.height || options.height == "") {
				if (options.onThisWindow) {
					options.height = isperp.appConfig.windowSize["big"][1] - 100;
				} else {
					options.height = isperp.appConfig.windowSize["big"][1];
				}
			}

		}
		if (options.url) {
			options.contentUrl = options.url;
		}

		if (options.contentUrl && options.id) {
			if (options.contentUrl.indexOf('?') != -1) {
				options.contentUrl += "&dialogId=" + options.id;
			} else {
				options.contentUrl += "?dialogId=" + options.id;
			}
		}

		options.contentUrl = encodeURI(options.contentUrl);

		if (options.buttons == undefined || options.buttons == null) {
			options.buttons = null;
		}

		var defaultcaptionButtons = {
			pin : {
				visible : false
			},
			refresh : {
				visible : true
			},
			toggle : {
				visible : false
			},
			minimize : {
				visible : false
			},
			maximize : {
				visible : options.maximize || true
			}
		};

		options.captionButtons = $.extend(defaultcaptionButtons, options.captionButtons);
		if (options.close == undefined)
			options.close = function(event, ui) {
				if (options.onThisWindow) {
					return;
				}
				var $this = $(this);
				$this.find("iframe").attr("src", "");
				if (isperp.dialogOpenedCount > 2) {
					var $pDialog = $("#dialog_" + (isperp.dialogOpenedCount - 2));

					if ($pDialog && $pDialog.length > 0) {
						$pDialog.find("iframe").each(function(index, item) {
							$(item.contentDocument).find("#loading-overlay").hide();
						});
					}
				} else {
					isperp.hideOverlay();
					// window.top.document.body.style.overflowY = "visible";
				}
				$("#" + event.target.id).remove();

				isperp.dialogOpenedCount = isperp.dialogOpenedCount - 1;

			};
		if (options.open == undefined)
			options.open = function(event, ui) {
				if (options.onThisWindow) {
					return;
				}
				// window.top.document.body.style.overflowY = "hidden";
				var $pDialog = $("#dialog_" + (isperp.dialogOpenedCount - 2));
				if ($pDialog.length == 1) {
					var $dialog = $("#dialog_" + (isperp.dialogOpenedCount - 1));
					// 如果子窗口较小则不需要偏移
					if (($pDialog.width() - $dialog.width()) > 15) {
						return;
					}
					$dialog.wijdialog("option", "position", {
						at : "left+51% top+51%",
						of : $pDialog
					});
				}
			};
	}

	isperp.reloadParentControl = function(pcontrolid) {
		pcontrolid = pcontrolid || isperp.getUrlParamByName("pcontrolid");

		isperp.reloadParentControlById(pcontrolid)
	};

	isperp.reloadParentControlById = function(pcontrolid) {
		if (pcontrolid == "undefined") {
			return false;
		}
		$("iframe").each(function(index, item) {
			if (pcontrolid && $(this).context.contentWindow.document.getElementById(pcontrolid)) {
				eval("$(this).context.contentWindow." + pcontrolid + ".reload();");
				return false;
			} else {
				var targetIframe = this;
				var isperpgrid = $(targetIframe).context.contentWindow.document.querySelector(".isperpgrid");
				if (isperpgrid != null) {
					try {
						eval("$(targetIframe).context.contentWindow." + isperpgrid.id + ".reload();");
					} catch (e) {
						isperp.errorAlert(e);
					}
				}
			}

		});
		if (top.location != self.location) {
			window.parent.isperp.reloadParentControlById(pcontrolid);
		}
	};

	isperp.excuteParentFucById = function(pcontrolid) {
		if (pcontrolid == "undefined") {
			return;
		}
		$("iframe").each(function(index, item) {
			if (pcontrolid && $(this).context.contentWindow.document.getElementById(pcontrolid)) {
				$(this).context.contentWindow.document.getElementById(pcontrolid).click();
			}

		});
		if (top.location != self.location) {
			window.parent.isperp.excuteParentFucById(pcontrolid);
		}
	};
	
	isperp.excuteParentFucByFuncName = function(funcName, para) {
		if (funcName == "undefined") {
			return;
		}
		window.top.$("iframe").each(function(index, item) {
			var meName = "$(this).context.contentWindow." + funcName;
			if (funcName && (typeof (eval(meName)) == "function")) {
				$(this).context.contentWindow.eval(funcName + "(" + para + ")");
			}
			try
			{
				$(this).context.contentWindow.$("iframe").each(function(index1, item1) {
					var meName1 = "$(this).context.contentWindow." + funcName;
					if (funcName && (typeof (eval(meName1)) == "function")) {
						$(this).context.contentWindow.eval(funcName + "(" + para + ")");
					}
				});
			}catch(e)
			{
				
			}
			
		});
		$("iframe").each(function(index, item) {
			var meName = "$(this).context.contentWindow." + funcName;
			if (funcName && (typeof (eval(meName)) == "function")) {
				$(this).context.contentWindow.eval(funcName + "(" + para + ")");
			}
		});

	};

	// 关闭对话框
	isperp.closeDialog = function(options, dialogId) {

		if (options && options.id && options.onThisWindow) {
			$("#" + options.id).wijdialog("close");

			if (options.callback) {
				options.callback();
			}
			return true;
		}
		var d = isperp.getUrlParamByName("dialogId");
		if (d) {
			dialogId = d;
		}

		if (top.location != self.location) {

			if (options && options.id) {
				options.onThisWindow = true;
			}
			window.parent.isperp.closeDialog(options, dialogId);
		} else {
			var $dialog;
			if (dialogId)
				$dialog = $("#" + dialogId);
			else
				$dialog = $("#dialog_" + (isperp.dialogOpenedCount - 1));

			if ($dialog.length == 1) {

				if (options && options.closeParent) {
					var $pDialog = $("#dialog_" + (isperp.dialogOpenedCount - 1));
					if ($pDialog.length == 1) {
						$pDialog.wijdialog("close");
					}
					$dialog.wijdialog("close");
				} else {
					$dialog.wijdialog("close");
				}
			} else {
				$dialog = $("#myWin_" + dialogId);
				if ($dialog.length == 1) {
					desktop.win.close($dialog);
				}
			}

			if (options && options.callback) {
				options.callback();
			}

		}
	};

	/**
	 * 刷新列表
	 */
	isperp.reloadGrid = function(gridId) {
		if ($("#" + gridId).length > 0) {
			eval(gridId + ".search()");
		} else if (top.location != self.location) {
			isperp.reloadParentControlById(gridId);
		}
	};

	isperp.getWindow = function(id) {
		return $("#" + id)[0].contentWindow;
	};

	// 异步提交表单
	isperp.submitForm = function(options) {

		var options = options || {};

		if (!options.error) {
			var afterError = function(XMLHttpRequest, textStatus, errorThrown) {

				isperp.alert("提交失败；" + XMLHttpRequest.responseText);
				// isperp.hideLoading();
			};

			options.error = function(XMLHttpRequest, textStatus, errorThrown) {
				afterError(XMLHttpRequest, textStatus, errorThrown);
			};
		}
		var isCloseDialog_ = true;
		if (options.isCloseDialog != undefined && options.isCloseDialog == false)
			isCloseDialog_ = false;
		var formId;
		if (options.formId) {
			formId = "#" + options.formId;
		} else {
			formId = "form";
		}
		if (!options.success) {
			options.success = function(data) {
				if (data && data.success == false) {
					isperp.errorAlert(data.data);
				} else {

					window.top.isperp.reloadParentControl(isperp.getUrlParamByName("pcontrolid"));
					if (isCloseDialog_) {
						isperp.closeDialog();
					}
					isperp.tooltip("表单保存成功！");
				}
			};
		}

		var result = null;
		if (options.isValidate) {
			result = true;
		} else {
			result = $(formId).valid();
		}

		if (!options.dataType) {
			options.dataType = "json";
		}

		// edit at 20150507
		if (result === true) {
			$(formId).ajaxSubmit(options);
		} else {
			var $scrollTo = $(".error:visible:first");
			var $mainCont = $("body"), scrollToValue = $scrollTo.offset().top - 30;
			$mainCont.scrollTop(scrollToValue);
			$mainCont.animate({
				scrollTop : scrollToValue
			});

		}
		return result;
	};

	// isperp=window.isperp;
	isperp.setNavpath = function(path) {
		var p = path.split('/');
		var html = "";
		for ( var i = 1; i < p.length; i++) {
			html += "<li><a href=\"javascript:void(0)\">" + p[i] + "</a></li>";
		}
		$("#main_nav").html(html);

	};

	isperp.toLocation = function(link) {
		var base = document.getElementsByTagName("base")[0].getAttribute("href");

		window.location.href = base + "/" + link;
	};

	isperp.showInWorkspace = function(link) {

		var $mainDiv = $("#dvContainer");

		if (typeof link == "string" || (link && (typeof link.substr == 'function'))) {

			$mainDiv.load(link);
			return false;
		}
		var $link = $(link);
		var hlink = $link.attr("href");
		if (hlink == "" || hlink == undefined) {
			// showMsg("功能链接未设定！");
			// alert("功能链接未设定！");
			isperp.alert("功能链接未设定！");
			return false;
		}

		hlink = encodeURI(hlink);

		isperp.setNavpath($link.attr("navpath"));
		var openType = $link.attr("openType");
		if (openType == "window") {
			isperp.openDialog({
				title : $link.text(),
				contentUrl : hlink,
				windowSize : 'big'
			});
			return;
		} else if (openType == "iframe") {

			$mainDiv.html("<iframe src='" + hlink + "'  style='width:100%;height:100%' scrolling='auto' frameborder='0'></iframe>");
			return;
		} else {
			$mainDiv.empty().load(hlink);
		}
	};

	isperp.download = function(url) {

		if (document.all) {
			var a = document.createElement("A");
			a.target = "_blank";
			a.href = url;
			document.body.appendChild(a);
			a.click();
			setTimeout(function() {
				a.parentNode.removeChild(a);
			}, 50);
		} else
			window.open(url, "_blank");
	};

	isperp.showOverlay = function() {
		$("#loading-overlay").show();
	};

	isperp.hideOverlay = function() {
		$("#loading-overlay").fadeOut($$.config.fxSpeed / 4);
	};

	isperp.showLoading = function(options) {
		var options = options || {};
		if (options.onThisWindow) {
			$("#loading-overlay").show();
			$("#loading").show();
		} else {
			window.top.isperp._showLoading();
		}
		// $("#loading-overlay").show()
	};

	isperp.hideLoading = function(options) {
		var options = options || {};
		if (options.onThisWindow) {
			$("#loading").hide();
			$("#loading-overlay").hide();
		} else {
			window.top.isperp._hideLoading();
		}
	};

	isperp._showLoading = function(options) {
		$("#loading").show();
	};

	isperp._hideLoading = function() {

		$("#loading").fadeOut();
		// $("#loading-overlay").fadeOut()
	};

	isperp.setEditor = function(id) {

	};

	isperp.showPopup = function(id) {

		var $item = $("#" + id), $box = $item.children('div');
		// ! Popup positioning
		$item.find('.popup').show().position({
			my : 'top',
			at : 'bottom',
			of : $item,
			offset : '10 15'
		}).show();

		// On shortcut click
		$item.click(function(e) {

			if ($item.hasClass('disabled')) {
				return false;
			}
			//
			// Hide other open popups
			// $item.children('div').fadeOut($$.config.fxSpeed, function() {
			// $item.removeClass('active');
			// });

			// Show the requested shortcut
			$box.fadeToggle($$.config.fxSpeed);
			$item.toggleClass('active');

			return false;
		});

		// Do not bubble up
		$box.click($$.utils.noBubbling);

		// ! Mail List
		var $mail = $item.find('.mail').has('.text');
		$mail.on('click', 'li', function() {
			$mail.find('.text:visible').slideUp($$.config.fxSpeed / 2);
			$(this).find('.text:hidden').slideToggle($$.config.fxSpeed / 2);
		}).on('hover', 'li', function() {
			$(this).toggleClass('normal');
		}).find('.text').hover(function() {
			$(this).parent('li').toggleClass('normal');
		}).click($$.utils.noBubbling);

	};

	isperp.scrollTop = function() {

		var $toTop = $('<a>', {
			href : '#top',
			id : 'gotoTop'
		}).appendTo('body'), $window = $(window);

		$window.scroll(_.debounce(function() {
			if (!jQuery.support.hrefNormalized) {
				$toTop.css({
					'position' : 'absolute',
					'top' : $window.scrollTop() + $window.height() - settings.ieOffset
				});
			}

			// If we are not at the top: fade out
			if ($window.scrollTop() >= 1) {
				$toTop.fadeIn();
			} else {
				// Else: fade in
				$toTop.fadeOut();
			}

		}, 300)).scroll();

		$toTop.click(function() {

			$("html, body").animate({
				scrollTop : 0
			});
			return false;

		});

	};

	/**
	 * 设定为向导式
	 */
	isperp.wizard = function(options) {
		var $this = $("#" + options.wizardId);
		// 初始设置
		var $el = {
			box : $this,
			content : $this.find('.content'),
			list : $this.find('.steps'),
			li_list : $this.find('.steps').find('li'),
			a_list : $this.find('.steps').find('a'),
			prev : $this.find('.actions').find('.left').find('a'),
			next : $this.find('.actions').find('.btn-next'),
			finish_btn : $this.find('.actions').find('a.finish'),
			finish : $this.find('.actions').find('.finish')
		};

		// !进入指定步骤
		var goToIndex = function(newIndex, $this) {
			// 旧步骤

			if (options.validataStep === true) {

				var $oldStepIndex = index;

				// 检查上一步是否可用，如果是最后一步则不检查//you bug
				if (newIndex > 0 && newIndex > $oldStepIndex && $el.finish.is(":hidden")) {
					var $ool = $($el.li_list[newIndex - 1]).find("a");

					if ($($ool.attr('href')).hasClass("current")) {
						isperp.alert("步骤：" + $ool.text() + "未完成！")
						return false;
					}
				}
			}

			try {
				var wizGoEvent = eval(options.wizardId + "_Event" + newIndex);
			} catch (e) {
				// undo anything
			}
			if (wizGoEvent) {
				var wizEventResult = wizGoEvent(newIndex, $this);
				if (wizEventResult === false) {
					return false;
				}
			}

			// 检查次数
			if (newIndex < 0) {
				return false;
			}

			if (newIndex == 0) {
				$el.prev.addClass('disabled');
			} else {
				$el.prev.removeClass('disabled');
			}

			if ((newIndex + 1) >= length) {
				$el.next.hide();
				$el.finish.css("display", "inline-block");

			} else {
				$el.next.css("display", "inline-block");
				$el.finish.hide();
			}

			$this.tabs({
				active : newIndex
			})

			index = newIndex;
		};
		var index = 0, length = 0;

		// ! Get number of steps
		length = $el.list.children().length;
		// ! Set up steps links
		$el.a_list.click(function(e) {
			e.preventDefault();
			goToIndex($(this).parent().index(), $this);
		});

		$el.prev.addClass('disabled');
		$el.prev.click(function(e) {
			e.preventDefault();
			goToIndex(index - 1, $this);
		});

		$el.next.click(function(e) {
			e.preventDefault();
			goToIndex(index + 1, $this);
		});

		$el.finish_btn.click(function(e) {
			e.preventDefault();
			goToIndex(length, $this);
		});

		// var gotoNextIndex = function() {
		// goToIndex(index + 1);
		// };

	};

	isperp.reloadPage = function() {
		location.reload();
	};
	isperp.createEasyTable = function(option) {
		var o = option;
		// 构造table
		var targetDivId = o.targetId;
		var relationId = o.relationId;
		var tableName = o.tableName;
		var columns = o.columns;
		var readOnly = o.readOnlly;
		var leg = columns.length + 1;
		if (readOnly)
			leg = columns.length;
		var tableStr = "<table style='width:100%' id='tb_" + tableName + "'>";
		if (!readOnly)
			tableStr += "<tr rd='tdaction_" + tableName + "'><td align='right' colspan='" + leg + "'><button id='addBtn_" + tableName + "' value='添加' style='margin-right:20px;'>添加</button></td></tr>";
		tableStr += "<table>";
		var headTrStr = "<tr style='background-color:#f5f5f5;height:30px;text-align:left;border-top:1px solid #cecece;'>";
		var columnNames = new Array();
		for ( var i = 0; i < columns.length; i++) {
			var label = columns[i].label;
			var name = columns[i].name;
			columnNames[i] = name;
			headTrStr += "<th style=\"width:" + columns[i].width + "\">" + label + "</th>";
		}
		if (!readOnly)
			headTrStr += "<th rd='tdaction_" + tableName + "'>操作</th>";
		headTrStr = headTrStr + "</tr>";
		$("#" + targetDivId).append(tableStr);
		$("#tb_" + tableName).append(headTrStr);
		isperp.createEasyTable.loadData(tableName, relationId, columns, readOnly);

		$("#addBtn_" + tableName).bind("click", function() {
			// alert(columns);
			$("#add_" + tableName).remove();
			$("#addDialog_"+tableName).remove();
			// 打开新窗口
			var thtml = "<div id='addDialog_"+tableName+"' style='height:500px'><table id='add_" + tableName + "' class='form-table'>";
			var tTrStr = "";
			// 哪些列需要添加
			for ( var i = 0; i < columns.length; i++) {
				var ttype = columns[i].dtype;
				tTrStr += "<tr><td class='td1'>" + columns[i].label + "</td><td class='td2'><input type='" + ttype + "' name='gc_" + columns[i].name + "'></td></tr>";
			}
			thtml += tTrStr + "</table></div>";
			$(thtml).dialog({
				resizable : true,
				modal : true,
				show : false,
				hide : false,
				height : 400,
				title : "添加",
				buttons : [ {
					text : "确定",
					"class" : "nui-mainbtn",
					click : function() {
						var jsonStr = "{";
						$("#add_" + tableName + " input[name^='gc_']").each(function() {
							var tname = $(this).attr("name");
							var tivalue = $(this).val();
							jsonStr += tname + ":'" + tivalue + "',";
						});
						jsonStr = jsonStr.substring(0, jsonStr.length - 1);
						jsonStr += "}";
						var tJsonData = eval('(' + jsonStr + ')');
						// 保存 并刷新列表
						$.ajax({
							url : 'incident/category/property/saveDataByTableAndRelationId?tableName=' + tableName + "&relationId=" + relationId,
							data : tJsonData,
							success : function(data) {
								isperp.createEasyTable.loadData(tableName, relationId, columns, readOnly);
							}
						});
						var dlg = $(this).dialog("close");
					}
				} ,{
					text : "关闭",
					"class" : "nui-mainbtn",
					click : function() {
						var dlg = $(this).dialog("close");
					}
				} ]

			});
			isperp.initElement("#add_" + tableName);
			//调整日期控件位置
			var scpt=$(document).scrollTop();
			var tp=$("[aria-describedby='addDialog_"+tableName+"'").css('top');
			tp=tp.replace(/px/,"");
			var rtop=(parseInt(tp)+scpt)+"px";
			$("[aria-describedby='addDialog_"+tableName+"'").css("position","absolute").css("top",rtop);
			
			
			return false;
		});
	};
	isperp.createEasyTable.view = function(columns) {
	}
	isperp.createEasyTable.addRow = function(tableId, rowObject) {

	}
	isperp.createEasyTable.deleteRow = function(tableName, rowId) {
		$.ajax({
			url : 'incident/category/property/deleteByTableAndRelationId',
			async : false,
			data : {
				tableName : tableName,
				id : rowId
			},
			success : function(data) {

			}
		});
	}
	isperp.createEasyTable.loadData = function(tableName, relationId, columns, readOnly) {
		$("#tb_" + tableName + " tr[data-tr]").remove();
		$.ajax({
			url : 'incident/category/property/getDataByTableAndRelationId',
			data : {
				tableName : tableName,
				relationId : relationId
			},
			success : function(data) {
				// alert(data);
				var trStr = "";
				var ifContainSumColumns = false;
				var sumColumnsName = "";
				var leg = columns.length + 1;
				var sumCount=0;
				for ( var i = 0; i < data.length; i++) {// 行
					var tdStr = "";
					for ( var j = 0; j < columns.length; j++)// 列
					{
						var tname = "data[" + i + "]." + columns[j].name;
						var width=columns[j].width;
						var tdata = eval(tname);
						if (columns[j].ifsum) {
							ifContainSumColumns = true;
							sumColumnsName = columns[j].name;
							sumCount+=parseInt(tdata);
						}
						
						tdStr += "<td row-id='"+data[i].id+"' row_column_name='"+columns[j].name+"' style='"+width+"'>" + tdata + "</td>";

					}
					if (!readOnly)
						tdStr += "<td rd='tdaction_" + tableName + "'><a id='dk_" + tableName + +data[i].id + "' data-id='" + data[i].id + "' class='nui-txt-link'>编辑</a><a id='ak_" + tableName + +data[i].id + "' data-id='" + data[i].id + "' class='nui-txt-link'>删除</a></td>";
					trStr += "<tr  data-tr='' row-id='"+data[i].id+"'>" + tdStr + "</tr>";
				}
				$("#tb_" + tableName).append(trStr);
				if (ifContainSumColumns)
					$("#tb_" + tableName).append("<tr data-tr=''><td colspan='" + leg + "'><label>合计：<span style='font-weight:bold'>"+sumCount+"</span></label></td></tr>");

				$("#tb_" + tableName + " a[id^='ak_']").delegate($("a[id^='ak_']"), "click", function() {
					isperp.createEasyTable.deleteRow(tableName, $(this).data("id"));
					isperp.createEasyTable.loadData(tableName, relationId, columns, readOnly);
				});
				$("#tb_" + tableName + " a[id^='dk_']").delegate($("a[id^='dk_']"), "click", function() {
					// 打开新窗口
					$("#edit_" + tableName).remove();
					$("#editDialog_"+tableName).remove();
					var thtml = "<div id='editDialog_"+tableName+"' style='height:500px'><table id='edit_" + tableName + "' class='form-table'>";
					var tTrStr = "";
					var id=$(this).data("id");
					
					// 哪些列需要添加
					for ( var i = 0; i < columns.length; i++) {
						var ttype = columns[i].dtype;
						var tvalue=$("[row-id='"+id+"'][row_column_name='"+columns[i].name+"']").text();
						tTrStr += "<tr><td class='td1'>" + columns[i].label + "</td><td class='td2'><input type='" + ttype + "' value='"+tvalue+"' name='gc_" + columns[i].name + "'></td></tr>";
					}
					thtml += tTrStr + "</table></div>";

					$(thtml).dialog({
						resizable : false,
						modal : true,
						show : false,
						hide : false,
						height : 400,
						title : "添加",
						buttons : [ {
							text : "确定",
							"class" : "nui-mainbtn",
							click : function() {
								var jsonStr = "{";
								$("#edit_" + tableName + " input[name^='gc_']").each(function() {
									var tname = $(this).attr("name");
									var tivalue = $(this).val();
									jsonStr += tname + ":'" + tivalue + "',";
								});
								jsonStr = jsonStr.substring(0, jsonStr.length - 1);
								jsonStr += "}";
								var tJsonData = eval('(' + jsonStr + ')');
								// 更新 并刷新列表
								$.ajax({
									url : 'incident/category/property/updateDataByTableAndId?tableName=' + tableName + "&id=" + id,
									data : tJsonData,
									success : function(data) {
										isperp.createEasyTable.loadData(tableName, relationId, columns, readOnly);
									}
								});
								var dlg = $(this).dialog("close");
							}
						} ,{
							text : "关闭",
							"class" : "nui-mainbtn",
							click : function() {
								var dlg = $(this).dialog("close");
							}
						} ]

					});
					
					isperp.initElement("#edit_" + tableName);
					//调整日期控件位置
					var scpt=$(document).scrollTop();
					var tp=$("[aria-describedby='editDialog_"+tableName+"'").css('top');
					tp=tp.replace(/px/,"");
					var rtop=(parseInt(tp)+scpt)+"px";
					$("[aria-describedby='editDialog_"+tableName+"'").css("position","absolute").css("top",rtop);
					
					
					//isperp.createEasyTable.loadData(tableName, relationId, columns, readOnly);
				});
			}
		});
	}

	// 根据当用用户对某个URL是否有访问权限
	// 非异步
	isperp.getCurUserRight = function(turl) {
		var result = true;
		$.ajax({
			async : false,
			url : "app/menu/getCurUserRight?turl=" + turl,
			success : function(data) {
				if (data == "false" || data == false)
					result = false;
			}
		});
		return result;
	}

	isperp.initElement = function(selector) {
		if (selector) {
			selector = selector + " ";
		} else {
			selector = "";
		}
		var revalidateInput = function() {
			if ($.validator) {
				var $el = $(this), $form = $el.parents('form'), validator = $form.data('validator');

				if (validator) {
					validator.element(this);
				}
			}
		};
		$(selector + ".form-table").each(function(index, table) {
			var $table = $(table);
			if (table.rows.length > 1 && table.rows[1].cells.length == 4) {
				var wi = $table.width();
				$table.find(".td2").css("width", ((wi - 240) / 2) + "px")
			}
		});
		$(selector + "label.required").html("<span class=\"required-tip\"><font color=\"red\"> * </font><font color=\"blue\">必填 </font>");
		// $("<span class=\"required-tip\"><font color=\"red\"> * </font><font
		// color=\"blue\">必填 </font>").not(".hide-required");

		$(selector + "input:text.required," + selector + "input[type=date].required," + selector + "input[type=datetime].required," + selector + "textarea.required," + selector + "select.required").not(".hide-required").after("<span class=\"required-tip\"><font color=\"red\"> * </font><font color=\"blue\">必填 </font>");

		// - Datepicker
		// See: http://bit.ly/mangoDPfix
		$.extend($.datepicker, {
			_checkOffset : function(inst, offset, isFixed) {
				return offset;
			}
		});

		$.extend($.datepicker._defaults, {
			showButtonPanel : true,
			showOtherMonths : true,
			changeYear : true,
			changeMonth : true,
			closeText : '关闭'
		});

		var datepickerEvents = {
			onSelect : revalidateInput,
			onClose : revalidateInput
		};

		$.extend($.datepicker._defaults, datepickerEvents);
		$.extend($.timepicker._defaults, datepickerEvents);

		$(selector + 'textarea').not('.editor').autosize();

		// Optional: Localization
		$(selector + 'input[type=date]').each(function() {
			var $el = $(this);

			$el[0].type = 'text';

			$el.datepicker();
		});
		$(selector + 'input[type=datetime]').each(function() {
			$(this).datetimepicker({
				controlType : 'select'
			}).blur(revalidateInput);
		});
		$(selector + 'input[type=time]').each(function() {
			$(this).timepicker({
				ampm : $(this).data('data-timeformat') == 12
			}).blur(revalidateInput);
		});

		// Create mirror input for inline datepicker
		var inline = {

			// Write date to mirror
			onselect : _.debounce(function(date, inst) {
				(inst.input || inst.$input).data('mirror').val(date);
			}, 300),

			// Create mirror
			setup : function($el) {
				var $mirror = $('<input>', {
					id : $el.data('id'),
					'class' : 'mirror',
					name : $el.data('name'),
					required : $el.attr('required') || 'false'
				}).hide().insertAfter($el);
				$el.data('mirror', $mirror);
			}
		};

		$(selector + 'div[data-type=date]').each(function() {
			var $this = $(this);
			inline.setup($this);
			$this.datepicker({
				onSelect : inline.onselect
			});
		});
		$(selector + 'div[data-type=datetime]').each(function() {
			var $this = $(this);
			inline.setup($this);
			$this.datetimepicker({
				onSelect : inline.onselect
			});
		});
		$(selector + 'div[data-type=time]').each(function() {
			var $this = $(this);
			inline.setup($this);
			$this.timepicker({
				onSelect : inline.onselect,
				ampm : $(this).data('data-timeformat') == 12
			});
		});

		// - Slider
		// $(selector + ' input[data-type=range]').mslider();

		(function() {
			var $slider = $('input.eq[data-type=range]').next();
			var zindex = $slider.length + 1;
			$slider.each(function() {
				$(this).css('z-index', zindex--);
			});
		})();

		// ! Select boxes
		var $cznSelects = $(selector + 'select').not(".ui-pg-selbox").not('.dualselects');
		$cznSelects.each(function() {
			var $el = $(this);
			var val = $el.find("option:selected");
			var valSelected = val.attr("selected");

			if ($el.data("allow-empty")) {
				$el.prepend('<option value="" ></option>');
				$el.val("");
			}
			if (valSelected != undefined) {
				$el.val(val.val());
			}
			$el.chosen({
				disable_search_threshold : $el.hasClass('search') ? 0 : Number.MAX_VALUE,
				allow_single_deselect : true,
				width : $el.data('width') || '155px',
				search_contains : true,
				no_results_text : "未找到此选项"

			});

		});

		// - Set up select boxes validation
		$(selector + '.chzn-done').on('change', function() {
			var validate = $(this).parents('form').validate();
			validate && validate.element($(this));
		}).each(function() {
			// - Set up form reset listener
			var $input = $(this), $form = $input.parents('form');

			$form.on('reset', function() {
				$input[0].selectedIndex = -1;
				$input.trigger('chosen:updated');
			});

			$form.data('chzn-reset', true);
		});

		// ! Uploader
		$(selector + '.uploader').each(function() {
			var $uploader = $(this);
			$uploader.pluploadQueue($.extend({
				runtimes : 'html5,flash,html4',
				url : '/uploader.php',
				max_file_size : '10mb',
				chunk_size : '1mb',
				unique_names : true,

				filters : [ {
					title : "图片文件",
					extensions : "jpg,gif,png"
				}, {
					title : "压缩文件",
					extensions : "zip"
				} ],

				flash_swf_url : 'js/mylibs/forms/uploader/plupload.flash.swf'
			}, $uploader.data()));
			$uploader.find('.plupload_button').addClass('button grey btn');
			$uploader.find('.plupload_add').addClass('icon-plus');
			$uploader.find('.plupload_start').addClass('icon-ok');
		});

		// ! Spinner
		$(selector + 'input[data-type=spinner]').each(function() {
			var $spinner = $(this), opts = $spinner.data();

			if (opts.format) {
				opts.numberformat = opts.format;
				opts.format = undefined;
			}
			$spinner.spinner(opts);
		});

	};

	(function($, window, document) {
		var PLUGIN_NAME = 'toggleFilter';
		$.fn[PLUGIN_NAME] = function(options) {

			return $(this).each(function() {
				//			
				var $table = $(this), opts = $.extend(true, {}, $.fn[PLUGIN_NAME].defaults, options, $table.data());

				var $filterBar = $table.next();

				if (opts.filterBar != 'none') {
					// Add button
					if (opts.filterBar != 'always') {
						var $toggleBtn = $table.click(function() {
							$filterBar.slideToggle($$.config.fxSpeed * 2 / 3, opts.callback);
							$toggleBtn.toggleClass('active');

						});

						// Show filter bar initially
						if (opts.showFilterBar) {
							$toggleBtn.addClass('active');
						}
					}

					// Show filter bar initially
					if (opts.filterBar == 'always' || opts.showFilterBar) {
						$filterBar.show();
					}

				}

			}); // End of '$(this).each(...)'

		};

		$.fn[PLUGIN_NAME].defaults = {
			filterBar : 'toggle', // One of: 'always', 'toggle, 'none'
			showFilterBar : false, // Show or hide the filter bar initially

			maxItemsPerPage : 5
		};

	})(jQuery, this, document);

	isperp.endProcess = function(processId) {
		isperp.confirmAlert('确定结束流程？', {
			yes : function() {
				$.post("workflow/processRun/endProcess", {
					processId : processId
				}, function(data, textStatus) {
					if (data.success) {
						isperp.tooltip("流程结束！");
						isperp.reloadParentControl();
					} else {
						isperp.alert(data.data);
					}
				}, "json");
			}
		});
	};

	isperp.loadMessageCount = function(data, all) {
		all = all || 0;
		if (data) {
			var ids = "";
			var d = data.content;
			if (d) {
				for ( var i = 0; i < d.length; i++) {
					ids += "," + d[i].id;
				}
				if (ids != "") {
					$.post("app/message/findCountsBySourceIds", {
						all : all,
						ids : ids
					}, function(result) {

						$(result).each(function(index, item) {
							var l = $("#msg_" + item.source_id);
							l.addClass("msg-link");
							l.html(item.count_t);
						});

					});
				}
			}
		}
	};

	isperp.formatDict = function(cellvalue, options, rowObject, dicts, showTitle, name, title) {

		var r = null;
		var result = "";
		for ( var i = 0; i < dicts.length; i++) {

			if (rowObject[name] == dicts[i].name) {
				var dict = dicts[i];
				if (dict.imgPath) {
					result += "<img src='" + dict.imgPath + "' title='" + title + "'  >"
				}
				if (showTitle) {
					if (dict.fontColor) {
						result += "<span style='color:" + dict.fontColor + "'>" + dict.name + "</span>";
					} else {
						result += dict.name;
					}
				}
				return result;
			}

		}

		return result;

	};

})(jQuery, this, document);

window.onload = function() {
	document.getElementsByTagName("body")[0].onkeydown = function() {
		// 获取事件对象
		var elem = event.relatedTarget || event.srcElement || event.target || event.currentTarget;
		if (event.keyCode == 8) {
			var elem = event.srcElement || event.currentTarget;
			var name = elem.nodeName;
			if (name != 'INPUT' && name != 'TEXTAREA') {
				return _stopIt(event);
			}
			var type_e = elem.type.toUpperCase();
			if (name == 'INPUT' && (type_e != 'TEXT' && type_e != 'TEXTAREA' && type_e != 'PASSWORD' && type_e != 'FILE')) {
				return _stopIt(event);
			}
			if (name == 'INPUT' && (elem.readOnly == true || elem.disabled == true)) {
				return _stopIt(event);
			}
		}
	};
};
function _stopIt(e) {
	if (e.returnValue) {
		e.returnValue = false;
	}
	if (e.preventDefault) {
		e.preventDefault();
	}

	return false;
}

String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {
	if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
		return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")), replaceWith);
	} else {
		return this.replace(reallyDo, replaceWith);
	}
};
String.prototype.trim = function() {
	return this.replace(/(^\s+)|\s+$/g, "");
};
/**
 * 转换字符串为json对象
 */
String.prototype.toJson = function() {
	return eval('(' + this + ')');
};

/* 替换成熟 */
String.prototype.replaceUrlParam = function(arg, arg_val) {
	var pattern = eval("/(\\?|\\&)" + arg + "=([^\\&]+)/");
	var replaceText = arg + '=' + arg_val;
	if (this.match(pattern)) {
		var tmp = '/(\\?' + arg + '=)([^&]*)/gi', targetUrl;
		targetUrl = this.replace(eval(tmp), "?" + replaceText);

		tmp = '/(\\&' + arg + '=)([^&]*)/gi';
		targetUrl = targetUrl.replace(eval(tmp), "&" + replaceText);

		return targetUrl;
	} else {
		if (this.match('[\?]')) {
			return this + '&' + replaceText;
		} else {
			return this + '?' + replaceText;
		}
	}
	return this + '\n' + arg + '\n' + arg_val;
};

/**
 * 输出2010-02-05格式的日期字符串
 * 
 * @return {}
 */
Date.prototype.toDateStr = function() {
	return ($.support.leadingWhitespace ? (this.getYear() + 1900) : (this.getYear())) + "-" + (this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : this.getMonth() + 1) + "-" + (this.getDate() < 10 ? "0" + this.getDate() : this.getDate());
};

/**
 * 日期格式化
 * 
 * @param {Object}
 *            format
 */
Date.prototype.format = function(format) {
	var o = {
		"M+" : this.getMonth() + 1, // month
		"d+" : this.getDate(), // day
		"h+" : this.getHours(), // hour
		"m+" : this.getMinutes(), // minute
		"s+" : this.getSeconds(), // second
		"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
		"S" : this.getMilliseconds()
	// millisecond
	};
	if (/(y+)/.test(format))
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
	return format;
};

/**
 * 将字符串格式的日期转换为日期类型对象
 * 
 * @param {Object}
 *            strDate
 */
Date.toDate = function(strDate) {
	var strDs = strDate.split('-');
	var year = parseInt(strDs[0], 10), month = parseInt(strDs[1] - 1, 10), date = parseInt(strDs[2], 10);
	return new Date(year, month, date);
};

/**
 * 通过当前时间计算当前周数
 */
Date.prototype.getWeekNumber = function() {
	var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
	var DoW = d.getDay();
	d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
	var ms = d.valueOf(); // GMT
	d.setMonth(0);
	d.setDate(4); // Thu in Week 1
	return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};

// +---------------------------------------------------
// | 日期计算
// +---------------------------------------------------
Date.prototype.DateAdd = function(strInterval, Number) {
	var dtTmp = this;
	switch (strInterval) {
	case 's':
		return new Date(Date.parse(dtTmp) + (1000 * Number));
	case 'n':
		return new Date(Date.parse(dtTmp) + (60000 * Number));
	case 'h':
		return new Date(Date.parse(dtTmp) + (3600000 * Number));
	case 'd':
		return new Date(Date.parse(dtTmp) + (86400000 * Number));
	case 'w':
		return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
	case 'q':
		return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
	case 'm':
		return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
	case 'y':
		return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
	}
};
// 修复jquery ui tabs 与 base 标签的bug
$.fn.__tabs = $.fn.tabs;
$.fn.tabs = function(a, b, c, d, e, f) {
	var base = location.href.replace(/#.*$/, '');
	$('ul>li>a[href^="#"]', this).each(function() {
		var href = $(this).attr('href');
		$(this).attr('href', base + href);
	});
	$(this).__tabs(a, b, c, d, e, f);
}
